package com.xiao.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.xiao.utils.FileUtil;
import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 阿里云 OSS 工具类
 */
@Setter
@Getter
@ToString
@AllArgsConstructor
@ConfigurationProperties(prefix = "oss") // 依赖 get set; 读取配置文件填充数据
@Component
public class OssUtils {
    private String endpoint;// 外网/内网 访问地域节点
    private String bucketName;// 填写Bucket名称，例如examplebucket。
    private EnvironmentVariableCredentialsProvider credentialsProvider;

    private PutObjectRequest putObjectRequest ;

    public  OssUtils() throws com.aliyuncs.exceptions.ClientException { // 无参构造 初始化数据
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量(他是从环境变量读取的) OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    }

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。 【外网访问地域节点】


    /**
     * 【文件上传】 同名会替换！！！
     * @param upLoadObjectName  上传到 OSS 的完整路径，不能包含Bucket名称，例如: exampledir/exampleobject.txt。 【路径加文件名称,不需要 / 开头】
     * @param multipartFile 上传目标的 MultipartFile [表单上传的文件]
     * @return 返回文件上传后外网路径，报错则 =""
     * @throws UnsupportedEncodingException
     */
    public String   upload(MultipartFile multipartFile, String upLoadObjectName) {
        System.out.println("------------"+getClass().toString()+"--------- Start ----");
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        String url="";// 文件上传后,外网路径
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, upLoadObjectName, multipartFile.getInputStream());
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            // URl地址有效期 加有效期，是为了拿到返回的地址[还不知道怎么拿到返回地址]
            Date date = new Date(/*new Date().getTime() + 3600l * 1000 * 24 * 365 * 10*/); // 十年

            // 返回 外网访问地址 [带有效期]
            String expireUrl = ossClient.generatePresignedUrl(bucketName, upLoadObjectName, date).toString();

            // 剔除有效期
            int index = expireUrl.lastIndexOf("?");
            url = expireUrl.substring(0, index);
            // 返回地址 【保证返回出来的地址是 外网访问地址】
            url=url.replace("-internal.aliyuncs.com",".aliyuncs.com");

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("-------- ClientException Start -------");

            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getErrorMessage());
            System.out.println("Error Code:" + ce.getErrorCode());
            System.out.println("Request ID:" + ce.getRequestId());
            System.out.println("Host ID:" + ce.toString());
            System.out.println("-------- ClientException End -------");

            throw new RuntimeException(ce);
        } catch (IOException e) {
            System.out.println("--超时异常--");
            throw new RuntimeException(e);

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }

            System.out.println("url: "+url);
            System.out.println("------------"+getClass().toString()+"--------- End ----");
            return url;
        }

    }
}
